import { AppDispatch, RootState } from "@/store";
import { usePathname } from "next/navigation";
import { findAllMenuItemByPath } from "@/config/menu";
import { useCallback, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import ACCESS_ENUM from "./accessEnum";
import { checkAccess } from "./checkAccess";
import { Forbidden } from "@/app/forbidden";

/**
 * 统一权限判断
 * @returns
 */
export const AccessLayout: React.FC<
  Readonly<{
    children: React.ReactNode;
  }>
> = ({ children }) => {
  // 获取当前路径
  const path = usePathname();
  // 获取当前用户
  const loginUser = useSelector((state: RootState) => state.user);
  const menu = findAllMenuItemByPath(path);
  const needAccess = menu?.access ?? ACCESS_ENUM.NOT_LOGIN;
  //校验权限
  const hasAccess = checkAccess(loginUser, needAccess);
  if (!hasAccess) {
    return <Forbidden />;
  }
  return children;
};
